<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班次编号" prop="shiftCode">
        <el-input
          v-model="queryParams.shiftCode"
          placeholder="请输入班次编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班次名称" prop="shiftName">
        <el-input
          v-model="queryParams.shiftName"
          placeholder="请输入班次名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-time-picker
          v-model="queryParams.startTime"
          placeholder="请选择开始时间"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          clearable
          style="width: 100%"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-time-picker
          v-model="queryParams.endTime"
          placeholder="请选择结束时间"
          value-format="HH:mm:ss"
          format="HH:mm:ss"
          clearable
          style="width: 100%"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否跨天" prop="isNextDay">
        <el-select v-model="queryParams.isNextDay" placeholder="请选择是否跨天" clearable>
          <el-option
            v-for="dict in sm_day"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in sm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['sm:shift:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sm:shift:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sm:shift:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['sm:shift:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shiftList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班次ID" align="center" prop="shiftId" />
      <el-table-column label="班次编号" align="center" prop="shiftCode" />
      <el-table-column label="班次名称" align="center" prop="shiftName" />
      <el-table-column label="开始时间" align="center" prop="startTime">
        <template #default="scope">
          {{ printTimeInfo(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime">
        <template #default="scope">
          {{ printTimeInfo(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="是否跨天" align="center" prop="isNextDay">
        <template #default="scope">
          <dict-tag :options="sm_day" :value="scope.row.isNextDay"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sm_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['sm:shift:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['sm:shift:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产班次对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="shiftRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="班次编号" prop="shiftCode">
              <el-input v-model="form.shiftCode" placeholder="请输入班次编号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班次名称" prop="shiftName">
              <el-input v-model="form.shiftName" placeholder="请输入班次名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-time-picker
                v-model="form.startTime"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                placeholder="请选择开始时间"
                style="width: 100%">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-time-picker
                v-model="form.endTime"
                value-format="HH:mm:ss"
                format="HH:mm:ss"
                placeholder="请选择结束时间"
                style="width: 100%">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否跨天" prop="isNextDay">
              <el-select v-model="form.isNextDay" placeholder="请选择是否跨天" style="width: 100%" >
                <el-option
                  v-for="dict in sm_day"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option
                  v-for="dict in sm_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Shift">
import { listShift, getShift, delShift, addShift, updateShift } from "@/api/sm/shift";
import { generateShiftCode } from "@/utils/generator";

const { proxy } = getCurrentInstance();
const { sm_status, sm_day } = proxy.useDict('sm_status', 'sm_day');

const shiftList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

// 格式化时间显示
function formatTime(timeStr) {
  if (!timeStr) return "";
  
  // 如果已经是HH:mm:ss格式，直接返回
  if (/^\d{2}:\d{2}:\d{2}$/.test(timeStr)) {
    return timeStr;
  }
  
  // 尝试处理可能的日期时间格式
  try {
    // 首先尝试提取时间部分
    const timeMatch = timeStr.match(/\d{2}:\d{2}:\d{2}/);
    if (timeMatch) {
      // 如果字符串中包含时间格式，直接提取
      return timeMatch[0];
    }
    
    // 处理ISO格式或其他格式的时间
    const date = new Date(timeStr);
    if (isNaN(date.getTime())) {
      console.error("无效的时间格式:", timeStr);
      return timeStr;
    }
    
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');
    
    return `${hours}:${minutes}:${seconds}`;
  } catch (e) {
    console.error("时间格式化错误:", e);
    return timeStr;
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shiftCode: null,
    shiftName: null,
    startTime: null,
    endTime: null,
    isNextDay: null,
    status: null,
  },
  rules: {
    shiftCode: [
      { required: true, message: "班次编号不能为空", trigger: "blur" }
    ],
    shiftName: [
      { required: true, message: "班次名称不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    isNextDay: [
      { required: true, message: "跨天不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询生产班次列表 */
function getList() {
  loading.value = true;
  listShift(queryParams.value).then(response => {
    shiftList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    shiftId: null,
    shiftCode: null,
    shiftName: null,
    startTime: null,
    endTime: null,
    isNextDay: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("shiftRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.shiftId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 自动生成班次编号
  form.value.shiftCode = generateShiftCode();
  open.value = true;
  title.value = "添加生产班次";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _shiftId = row.shiftId || ids.value
  getShift(_shiftId).then(response => {
    // 获取数据
    form.value = response.data;
    
    // 只保留时间部分，格式为HH:mm:ss
    if (form.value.startTime) {
      form.value.startTime = formatTime(form.value.startTime);
    }
    if (form.value.endTime) {
      form.value.endTime = formatTime(form.value.endTime);
    }
    
    open.value = true;
    title.value = "修改生产班次";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["shiftRef"].validate(valid => {
    if (valid) {
      // 创建一个新的表单数据对象，避免修改原始表单
      const formData = { ...form.value };

      // 确保时间格式为HH:mm:ss
      if (formData.startTime) {
        formData.startTime = formatTime(formData.startTime);
      }
      
      if (formData.endTime) {
        formData.endTime = formatTime(formData.endTime);
      }
      
      if (form.value.shiftId != null) {
        updateShift(formData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error('更新失败:', error);
        });
      } else {
        addShift(formData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(error => {
          console.error('添加失败:', error);
        });
      }
    }
  });
}

// 显示调试信息
function printTimeInfo(time) {
  if (!time) return '';
  // 直接调用格式化函数处理时间
  return formatTime(time);
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _shiftIds = row.shiftId || ids.value;
  proxy.$modal.confirm('是否确认删除生产班次编号为"' + _shiftIds + '"的数据项？').then(function() {
    return delShift(_shiftIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('sm/shift/export', {
    ...queryParams.value
  }, `shift_${new Date().getTime()}.xlsx`)
}

getList();
</script>
